package com.itawei.d2_UDP2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class ReceiveMessage {
    public static void main(String[] args) throws IOException {
        //UDP 接收数据：因为接收端不知道发送端什么时候停止发送，故采用死循环接收
        //1.创建一个DategramSocket对象，准备接收数据
        DatagramSocket ds = new DatagramSocket(10086);//10086端口接收数据
        //2.接收数据
        //2.1创建一个包和字节数组
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
        while (true) {
            //3.解析包
            ds.receive(dp);
            //4.打印数据
            byte[] data = dp.getData();
            InetAddress address = dp.getAddress();//接收到发送端IP地址
            int port = dp.getPort();//接收到发送端端口号

            System.out.println("一个"+address.getHostName()+"的人，IP地址为"+address.getHostAddress()+"发送了数据:"+
                    new String(bytes,0,dp.getLength()));
        }
    }
}
